<script setup lang="ts">
import VDialog from "@/components/VDialog/VDialog.vue";
import { computed, reactive, ref, watch } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { downloadTemplateApi, importDataApi } from "@/api/airport/dataManage/sirSelfCheck";

interface Props {
  modelValue: boolean;
  deptTree?: any[];
}

const props = defineProps<Props>();
const emits = defineEmits<{
  (e: "update:modelValue", v: boolean): void;
  (e: "success"): void;
}>();

const visible = computed({
  get: () => props.modelValue,
  set(v) {
    emits("update:modelValue", v);
  }
});

const title = computed(() => {
  return "导入部门数据";
});

const formData = reactive({
  belongDept: undefined,
  file: null as File | null
});

const rules: FormRules = {
  belongDept: [{ required: true, message: "请选择部门", trigger: "change" }]
};

const formRef = ref<FormInstance>();
const loading = ref(false);
const uploadRef = ref();

// 下载模板
async function handleDownloadTemplate() {
  try {
    await downloadTemplateApi();
    ElMessage.success("模板下载成功");
  } catch (error) {
    ElMessage.error("模板下载失败");
    console.error("下载模板失败:", error);
  }
}

// 处理文件选择
function handleFileChange(file: File) {
  formData.file = file;
}

// 上传文件
async function handleConfirm() {
  try {
    await formRef.value?.validate();

    if (!formData.file) {
      ElMessage.warning("请选择要上传的Excel文件");
      return;
    }

    loading.value = true;
    const response = await importDataApi(formData.file, formData.belongDept);

    ElMessage.success(`导入成功，新增${response.data.added}条数据`);
    visible.value = false;
    emits("success");
  } catch (e) {
    console.error("导入失败:", e);
    ElMessage.error("导入失败，请检查文件格式是否正确");
  } finally {
    loading.value = false;
  }
}

watch(
  () => props.modelValue,
  val => {
    if (val) {
      // Reset form when modal opens
      formRef.value?.resetFields();
      formData.belongDept = undefined;
      formData.file = null;
    }
  }
);
</script>

<template>
  <v-dialog
    :title="title"
    v-model="visible"
    :loading="loading"
    @confirm="handleConfirm"
    @cancel="visible = false"
    class="small-update-modal"
    width="500px"
  >
    <div style="margin-top: 20px; margin-left: 30px; margin-right: 30px;">
      <!-- 导入教程文字 -->
      <div style="margin-bottom: 20px; padding: 10px; background-color: #f5f7fa; border-radius: 4px;">
        <p style="font-size: 14px; line-height: 1.6;">
          <strong>导入教程：</strong><br>
          1. 先点击下方的"下载模板"按钮下载Excel模板文件<br>
          2. 在模板中粘贴数据表格（注意不要出现任何格式）<br>
          3. 选择要导入数据的归属部门<br>
          4. 点击"上传"按钮选择填好的Excel文件进行上传
        </p>
      </div>

      <!-- 表单 -->
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="归属部门" prop="belongDept">
          <el-cascader
            v-model="formData.belongDept"
            :options="deptTree"
            :props="{
              value: 'value',
              label: 'label',
              emitPath: false,
              checkStrictly: true
            }"
            clearable
            placeholder="请选择部门"
            class="!w-[200px]"
          />
        </el-form-item>

        <el-form-item style="margin-top: 30px;">
          <el-button type="primary" @click="handleDownloadTemplate">
            下载模板
          </el-button>
          <el-upload
            ref="uploadRef"
            :show-file-list="false"
            :before-upload="(file) => { handleFileChange(file); return false; }"
            class="ml-4"
          >
            <el-button type="primary">
              上传文件
            </el-button>
          </el-upload>
          <div v-if="formData.file" class="mt-2 text-success">
            已选择文件: {{ formData.file.name }}
          </div>
        </el-form-item>
      </el-form>
    </div>
  </v-dialog>
</template>

<style>
.small-update-modal .el-dialog__body {
  height: 400px !important; /* 增加高度以容纳教程文字和上传组件 */
  overflow-y: auto !important;
}
</style>
